public class Flatten {
    // leetcode 二叉树展开为链表
    // https://leetcode.cn/problems/flatten-binary-tree-to-linked-list/description/?envType=study-plan-v2&envId=top-100-liked
    public void flatten(TreeNode root) {
        flattenChild(root);
    }

    private TreeNode flattenChild(TreeNode root) {
        if (root == null) return null;
        TreeNode leftNode = flattenChild(root.left);
        TreeNode rightNode = flattenChild(root.right);
        if (leftNode != null) {
            leftNode.left = null;
            TreeNode cur = leftNode;
            while (cur.right != null) {
                cur = cur.right;
            }
            cur.right = rightNode;
            root.right = leftNode;
            root.left = null;
        }
        return root;
    }
}
